<template>
  <div class="loginbody">
    <div class="logindata">
      <div class="logintext">
        <h2>里程碑</h2>
      </div>
      <div class="formdata">
        <el-form v-if="islogin" ref="loginRef" :model="form" :rules="rules">
          <el-form-item label="用户" style="font-weight: bold;" prop="username">
            <el-input v-model="form.username" clearable placeholder="请输入账号" />
          </el-form-item>
          <el-form-item label="密码" style="font-weight: bold;" prop="password">
            <el-input v-model="form.password" clearable placeholder="请输入密码" show-password></el-input>
          </el-form-item>
          <div class="tool">
            <el-checkbox v-model="checked" @change="remember">记住密码</el-checkbox>
            <el-link class="shou" @click="forgetpas">忘记密码？</el-link>
          </div>
          <div class="butt">
            <el-button type="primary" @click="login(loginRef)">登录</el-button>
            <el-button class="shou" @click="registerJump">注册</el-button>
          </div>
        </el-form>
        <el-form v-if="!islogin" ref="loginRef" :model="form" :rules="rules">
          <el-form-item label="用户名称" style="font-weight: bold;" prop="username">
            <el-input v-model="form.username" clearable placeholder="请输入账号" />
          </el-form-item>
          <el-form-item label="登录密码" style="font-weight: bold;" prop="password">
            <el-input v-model="form.password" clearable placeholder="请输入登录密码" show-password></el-input>
          </el-form-item>
          <el-form-item label="确认密码" style="font-weight: bold;" prop="confirmPassword">
            <el-input v-model="form.confirmPassword" clearable placeholder="请输入确认密码" show-password></el-input>
          </el-form-item>
          <div class="butt">
            <el-button type="default" @click="goBackPath">取消</el-button>
            <el-button v-if="isChangePwd" class="shou" type="primary" @click="register">注册</el-button>
            <el-button v-if="!isChangePwd" class="shou" type="primary" @click="changepwd">修改密码</el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
// import { login } from "@/api/login";
import { reactive } from '@vue/reactivity'
import { ElMessage } from 'element-plus'
// import { useRouter } from 'vue-router'
// const router = useRouter()
const axios = require('axios')
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value !== this.form.password) {
        callback(new Error('登录密码和确认密码不一致,请重新输入'))
        this.form.confirmPassword = ''
      } else {
        callback()
      }
    }
    return {
      form: reactive({
        password: "",
        username: "",
        confirmPassword: ""
      }),
      islogin: true,
      isChangePwd: true,
      checked: false,
      rules: reactive({
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "请输入3-10个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 10, message: "请输入3-10个字符", trigger: "blur" },
        ],
        confirmPassword: [
          { required: true, message: "请输入确认密码", trigger: "blur" },
          { min: 3, max: 10, message: "请输入3-10个字符", trigger: "blur" },
          { validator: validatePass, trigger: "blur" },
        ]
      })
    };
  },
  mounted() {
    if (localStorage.getItem("news")) {
      this.form = JSON.parse(localStorage.getItem("news"))
      this.checked = true
    }
  },
  methods: {
    login() {
      this.$refs.loginRef.validate((valid) => {
        if (valid) {
          // 后台登录
          const path = 'http://39.101.129.87:5001/login'
          let post_data = {
            "user-name": this.form.username,
            "user-pwd": this.form.password
          }
          let header = { headers: { 'Content-Type': 'application/json' } }
          axios.post(path, post_data, header).then(res => {
            if (res.data.code === 1) {
              ElMessage({ message: '登录成功，正在跳转', type: 'success', })
              // 跳转到主页面，传递参数用户名
              this.$router.push({ name: 'main', query: { user: this.form.username } })
            } else if (res.data.code === 2) {
              ElMessage({ message: '密码不正确，请重新输入', type: 'error', })
              this.form.password = ''
            } else if (res.data.code === 3) {
              ElMessage({ message: '用户名不存在，请先进行注册', type: 'error', })
              this.islogin = false
              this.form.password = ''
              this.form.confirmPassword = ''
            }
          }).catch(error => { console.error(error); });
        } else {
          ElMessage({ message: '用户名密码不符合规范', type: 'error', })
        }
      })
    },
    remember(data) {
      this.checked = data
      if (this.checked) {
        localStorage.setItem("news", JSON.stringify(this.form))
      } else {
        localStorage.removeItem("news")
      }
    },
    forgetpas() {
      // 显示修改界面
      this.islogin = false
      this.isChangePwd = false
    },
    changepwd() {
      this.$refs.loginRef.validate((valid) => {
        if (valid) {
          // 1.查询用户是否存在，用户存在才允许修改密码
          const path = 'http://39.101.129.87:5001/login'
          let post_data = {
            "user-name": this.form.username,
            "user-pwd": this.form.password
          }
          let header = { headers: { 'Content-Type': 'application/json' } }
          axios.post(path, post_data, header).then(res => {
            // 用户存在才允许修改密码
            if (res.data.code !== 3) {
              const path = 'http://39.101.129.87:5001/change_pwd'
              let post_data = {
                "user-name": this.form.username,
                "user-pwd": this.form.password
              }
              let header = { headers: { 'Content-Type': 'application/json' } }
              axios.post(path, post_data, header).then(res => {
                if (res.data.code === 0) {
                  ElMessage({ message: '用户密码修改成功', type: 'success' })
                  this.islogin = true
                }
              }).catch(error => { console.error(error); });
            } else {
              ElMessage({ message: '用户信息不存在，请先注册', type: 'error', })
            }
          }).catch(error => { console.error(error); });
        } else {
          ElMessage({ message: '用户名密码不符合规范', type: 'error', })
        }
      })
    },
    registerJump() {
      // 跳转注册页
      this.islogin = false
    },
    goBackPath() {
      this.islogin = true
    },
    register() {
      this.$refs.loginRef.validate((valid) => {
        if (valid) {
          // 1.查询用户是否存在，用户存在才允许修改密码
          const path = 'http://39.101.129.87:5001/login'
          let post_data = {
            "user-name": this.form.username,
            "user-pwd": this.form.password
          }
          let header = { headers: { 'Content-Type': 'application/json' } }
          axios.post(path, post_data, header).then(res => {
            // 用户不存在才允许注册
            if (res.data.code === 3) {
              const path = 'http://39.101.129.87:5001/register'
              let post_data = {
                "user-name": this.form.username,
                "user-pwd": this.form.password
              }
              let header = { headers: { 'Content-Type': 'application/json' } }
              axios.post(path, post_data, header).then(res => {
                if (res.data.code === 0) {
                  ElMessage({ message: '注册成功，请登录', type: 'success' })
                  this.islogin = true
                }
              }).catch(error => { console.error(error); });
            } else {
              ElMessage({ message: '用户信息已存在，请登录', type: 'error', })
            }
          }).catch(error => { console.error(error); });
        } else {
          ElMessage({ message: '用户名密码不符合规范', type: 'error', })
        }
      })
    }
  },
}

</script>

<style scoped>
.loginbody {
  width: 100%;
  height: 100%;
  background: url("../assets/bk.jpg") center center no-repeat;
  background-size: 100% 100%;
  /* overflow: auto; */
  position: fixed;
  line-height: 100%;
  padding-top: 150px;
}

.logintext {
  margin-bottom: 20px;
  line-height: 50px;
  text-align: center;
  font-size: 30px;
  font-weight: bolder;
  color: white;
  text-shadow: 2px 2px 4px #000000;
}

.logindata {
  width: 400px;
  height: 300px;
  transform: translate(-50%);
  margin-left: 50%;
}

.tool {
  display: flex;
  justify-content: space-between;
  color: #606266;
}

.butt {
  margin-top: 10px;
  text-align: center;
}

.shou {
  cursor: pointer;
  color: #606266;
}
</style>

